package com.bosicen.crm.web.controller.orders;

import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.bosicen.crm.dao.entity.Order;
import com.bosicen.crm.dao.entity.OrderDetail;
import com.bosicen.crm.dao.entity.ProductSery;
import com.bosicen.crm.dao.entity.User;
import com.bosicen.crm.service.CommonServiceImpl;
import com.bosicen.crm.service.orders.OrdersServiceImpl;
import com.bosicen.crm.tools.AppUtil;
import com.bosicen.crm.tools.Page;
import com.google.gson.Gson;

/****
 * 订单操作  controller
 * @author Administrator
 *
 */

@Controller
@RequestMapping("/orders")
public class OrdersController {

	@Autowired
	private OrdersServiceImpl ordersservice;
	@Autowired
	CommonServiceImpl commonService;
	/****
	 * 查询单个详细订单信息
	 * @param request
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/findorderdatail/{id}")
	public String findOrderDetail(HttpServletRequest request,@PathVariable("id") Integer id){
		OrderDetail od=this.ordersservice.findOrderDetail(id);
		request.setAttribute("od", od);
		return "orders/order_detail";
	}
	/****
	 *  订单查询信息
	 * @param request
	 * @param pagesize
	 * @return
	 */
	@RequestMapping(value="/findorders/{pagesize}/{type}")
	public String findOrders(Order order,HttpServletRequest request,@PathVariable("pagesize") Integer pagesize,@PathVariable("type") Integer type){
		
		Page page=new Page();
		page.setEveryPage(pagesize);
		page.setCurrentPage(AppUtil.ObjectToInt(request.getParameter("pageno")));
		page=this.ordersservice.findOrder(order, page);
		if(page==null){
			request.setAttribute("msg", "无相关信息,请重新查询");
		}
		request.setAttribute("page", page);
		//type 为跳转的类型 
		return "orders/order_list";
	}
	/****
	 * 新增订单信息
	 * @param order
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/addorders")
	public ModelAndView saveOrders(Order order,HttpServletRequest request){
		try{
			User user=(User) request.getSession().getAttribute("userinfo");
			order.setSysinsertdate(new Date());
			if(AppUtil.ObjectToString(order.getStartdate())!=null) order.setCreatedate(AppUtil.StringToDate(order.getStartdate(), "yyyy-MM-dd"));
			if(AppUtil.ObjectToString(order.getEnddate())!=null) order.setExdeliverydate(AppUtil.StringToDate(order.getEnddate(), "yyyy-MM-dd"));
			order.setCompanyid(user.getCompanyid());
			
			
			boolean flag=this.ordersservice.saveOrUpdateOrders(order);
			if(flag&&AppUtil.ObjectToInt(order.getId())>0){
				return new ModelAndView("redirect:/orders/findOrderById/"+order.getId());
			}else{
				request.setAttribute("msg", "操作失败,请重新操作");
				request.setAttribute("order", order);
			}
		}catch(Exception ex){
			ex.printStackTrace();
			request.setAttribute("msg", "系统出现异常,请重新操作");
		}
		return new ModelAndView("orders/addorder");
	}
	
	/****
	 * 新增订单详细
	 * @param request
	 * @param detail
	 */
	@RequestMapping(value="/addOrderDetail/{orderid}")
	public void saveOrderDetails(HttpServletRequest request,OrderDetail detail,@PathVariable("orderid") Integer orderid,Writer writer){
		Gson gson=new Gson();
		try{
			User user=(User) request.getSession().getAttribute("userinfo");
			detail.setCreatedate(new Date());
			detail.setAlive(0);
			detail.setCompanyid(user.getCompanyid());
			detail.setFlag(this.ordersservice.saveOrderDetails(orderid, detail));
			detail.setPid(orderid);
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			try{
			writer.write(gson.toJson(detail));
			}catch(Exception x){
				x.printStackTrace();
			}
		}
		
	}
	
	/****
	 * 通过订单id查询详细订单
	 * @param request
	 * @param orderid
	 * @return
	 */
	@RequestMapping(value="/findOrderById/{orderid}")
	public String findOrderById(HttpServletRequest request,@PathVariable("orderid") Integer orderid){
		try{
			Order order=this.ordersservice.findOrderById(orderid);
			if(order!=null){
				List<Object[]> list=this.ordersservice.findOrderDetailByType(orderid);
				int i=0;float price=0;
				for(Object[] obj:list){
					i++;
					request.setAttribute("count_"+obj[0],obj[1]);
					Iterator it=order.getOrderdetail().iterator();
					List<OrderDetail> detail=new ArrayList<OrderDetail>();
					while(it.hasNext()){
						OrderDetail de=(OrderDetail) it.next();
						if(i==1) price+=de.getPrice();
						if(de.getType()==AppUtil.ObjectToInt(obj[0])){
							
							ProductSery ps=this.commonService.findProductSeryByProductid(de.getProductid());
						   if(ps!=null) de.setProductsery(ps.getName());
						    detail.add(de);
						}
					}
					request.setAttribute("list_"+obj[0], detail);
				}
				request.setAttribute("total_price", price);
				request.setAttribute("order", order);
			}else{
				request.setAttribute("msg", "查询失败,该订单不存在");
			}
		}catch(Exception ex){
			ex.printStackTrace();
			request.setAttribute("msg", "系统出现异常,请重新操作");
		}
		
		return "orders/order_detail_list";
	}
	

	
	/***
	 * 删除订单详细信息 
	 * @param request
	 * @return
	 */
	@RequestMapping(value="/delordersdetail/{detailid}")
	public void delOrdersDetail(HttpServletRequest request,@PathVariable("detailid") Integer detailid,Writer writer){
		
		Gson gson=new Gson();
		boolean flag=false;
		try{
			flag=this.ordersservice.delOrderDetail(detailid);
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			try{
			writer.write(gson.toJson(flag));
			}catch(Exception x){
				x.printStackTrace();
			}
		}
	}
	
	
	
}
